<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 站点模块菜单 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\model;

use think\Db;
use think\Model;

class SiteModuleMenu extends Model {

    private static function _q() {
        return Db::name("site_module_menu");
    }

    /**
     * 增加模块菜单
     *
     * @param $mid
     * @param $menus
     */
    public static function createMenus($mid, $menus) {
        foreach ($menus as $menu) {
            $data = [
                'module_id' => $mid,
                'title' => $menu['title'],
                'link' => $menu['link'],
                'img' => fetch($menu, 'img'),
                'type' => 'menu',
                'sort' => isset($menu['sort']) ? $menu['sort'] : 10,
                'authority' => $menu['authority']
            ];
            $id = self::_q()->insertGetId($data);
            if (isset($menu['sub'])) {
                foreach ($menu['sub'] as $subMenu) {
                    $data = [
                        'module_id' => $mid,
                        'title' => $subMenu['title'],
                        'link' => $subMenu['link'],
                        'img' => fetch($subMenu, 'img'),
                        'type' => 'menu',
                        'sort' => isset($subMenu['sort']) ? $subMenu['sort'] : 10,
                        'authority' => $subMenu['authority'],
                        'parent_id' => $id
                    ];
                    self::_q()->insertGetId($data);
                }
            }
        }
    }

    /**
     * 增加模块前台入口地址
     *
     * @param $mid
     * @param $entries
     */
    public static function createEntries($mid, $entries) {
        foreach ($entries as $entry) {
            $data = [
                'module_id' => $mid,
                'title' => $entry['title'],
                'link' => $entry['link'],
                'img' => fetch($entry, 'img'),
                'type' => 'entry',
                'sort' => isset($entry['sort']) ? $entry['sort'] : 10,
                'authority' => $entry['authority']
            ];
            self::create($data);
        }
    }

    /**
     * 删除模块相关的全部菜单和入口
     *
     * @param $mid
     * @return int
     */
    public static function deleteByMid($mid) {
        $query = new self();
        return $query->where(['module_id' => $mid])->delete();
    }
}